package com.flyduck.modules.app.interceptor;

import com.flyduck.modules.app.annotation.Login;
import com.flyduck.common.exception.BusinessException;
import com.flyduck.modules.app.constant.AppConstant;
import com.flyduck.utils.JwtUtils;
import com.flyduck.utils.StringUtils;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: vueshop
 * @description:
 * @author: flyduck
 * @create: 2024-05-18 08:27
 **/
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Resource
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 没有@Login注解，直接放行
        if(handler instanceof HandlerMethod){
            Login annotation = ((HandlerMethod)handler).getMethodAnnotation(Login.class);
            if (annotation == null){
                return true;
            }
        }else {
            return true;
        }

        // 有@Login注解，获取token
        String token = request.getHeader(AppConstant.TOKEN_HEADER_KEY);

        // token不存在，提示登录
        if(StringUtils.isBlank(token)){
            throw new BusinessException(401,"请先登录");
        }

        // token过期了，
        Claims claim = jwtUtils.getClaimByToken(token,"APP");
        if (claim == null || jwtUtils.isTokenExpired(claim.getExpiration())) {
            throw new BusinessException(401,"请先登录");
        }

        // 把用户信息存储到session里面
        request.getSession().setAttribute(AppConstant.SESSION_USER_KEY, Long.parseLong(claim.getSubject()));
        return true;
    }
}
